package com.csun.cmny.provider.device.csun.sleep;

import com.csun.cmny.config.properties.CmnyProperties;
import com.csun.cmny.provider.device.csun.sleep.entity.CsunSleepData;
import com.csun.cmny.provider.model.vo.csunsleep.DmcCsunSleepVo;
import com.csun.cmny.provider.service.DmcCsunSleepBindService;
import com.csun.cmny.provider.utils.DateUtil;
import com.csun.cmny.util.RedisKeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-03-05 18:02
 * @Description:
 */
@Slf4j
@Configuration
public class SleepInitRunner implements CommandLineRunner {

    @Resource
    private CmnyProperties cmnyProperties;

    @Resource
    private DmcCsunSleepBindService dmcCsunSleepBindService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void run(String... args) throws Exception {

        List<DmcCsunSleepVo> csunSleepVos = dmcCsunSleepBindService.queryCsunSleepBindListAll();
        for (DmcCsunSleepVo csunSleepVo : csunSleepVos) {
            CsunSleepData csunSleepData = new CsunSleepData();
            csunSleepVo2Data(csunSleepVo, csunSleepData);
            redisTemplate.opsForValue().set(RedisKeyUtil.getCsunSleepKey(csunSleepData.getDeviceNo()),
                    csunSleepData);
        }

        log.info("###SleepInitRunner，finish<<<<<<<<<<<<<");
    }

    public void csunSleepVo2Data(DmcCsunSleepVo csunSleepVo, CsunSleepData csunSleepData) {
        csunSleepData.setDeviceId(csunSleepVo.getId());
        csunSleepData.setDeviceNo(csunSleepVo.getDeviceNo());
        csunSleepData.setGroupId(csunSleepVo.getGroupId());
    }

    @Bean
    public MessageChannel sleepSubChannel() {
        return new DirectChannel();
    }

    @Bean
    public MessageChannel sleepPubChannel() {
        return new DirectChannel();
    }

    @Bean
    public MqttPahoClientFactory sleepClientFactory() {
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setServerURIs(cmnyProperties.getMqtt().getSleep().getHost().split(","));
        mqttConnectOptions.setUserName(cmnyProperties.getMqtt().getSleep().getUsername());
        mqttConnectOptions.setPassword(cmnyProperties.getMqtt().getSleep().getPassword().toCharArray());
        mqttConnectOptions.setKeepAliveInterval(60);
        mqttConnectOptions.setConnectionTimeout(30);

        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(mqttConnectOptions);

        return factory;
    }

    @Bean
    public MessageProducer sleepMessageProducer() {

        String[] topics = cmnyProperties.getMqtt().getSleep().getTopic().split(",");

        MqttPahoMessageDrivenChannelAdapter adapter =
                new MqttPahoMessageDrivenChannelAdapter(cmnyProperties.getMqtt().getSleep().getHost(),
                        cmnyProperties.getMqtt().getSleep().getSubClientId()
                                + DateUtil.dateToStrs(new Date()),
                        sleepClientFactory(), topics);

        adapter.setCompletionTimeout(30000);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(1);
        adapter.setOutputChannel(sleepSubChannel());

        return adapter;
    }

    @Bean
    @ServiceActivator(inputChannel = "sleepSubChannel")
    public MessageHandler sleepMessageHandler() {

        return new SleepMessageHandler(cmnyProperties.getMqtt().getSleep().getDuration());
    }

    @Bean
    @ServiceActivator(inputChannel = "sleepPubChannel")
    public MessageHandler sleepPubMessageHandler() {
        MqttPahoMessageHandler messageHandler =
                new MqttPahoMessageHandler(cmnyProperties.getMqtt().getSleep().getPubClientId()
                        + DateUtil.dateToStrs(new Date()),
                        sleepClientFactory());
        messageHandler.setAsync(true);
        messageHandler.setDefaultTopic("God");

        return messageHandler;
    }
}
